package controller;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.google.gson.Gson;
import local.SystemUserFacadeLocal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import local.BufferFacadeLocal;
import model.SystemUser;
import util.AccessMap;
import util.JsonReturnMsg;

/**
 *
 * @author Randy
 */
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {

    @EJB
    SystemUserFacadeLocal suFacade;
    @EJB
    BufferFacadeLocal bFacade;
    Gson gson = new Gson();
    private String json;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            if (action.equals("login")) {
                processLogin(request, response);

            } else if (action.equals("logout")) {
                processLogout(request, response);
            }
            
        } catch (Exception ex) {
            json = gson.toJson(new JsonReturnMsg("Error", ex.getMessage(), "error"));
            response.getWriter().println(json);
        } finally {
            response.getWriter().close();
        }
    }

    private void processLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        bufferInstantiation();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        SystemUser su = suFacade.getCredentials(username, password);

        if (su == null) {
            json = gson.toJson(new JsonReturnMsg("IEPM Login", "Invalid login credentials", "error"));
        } else {
            HttpSession session = request.getSession();
            session.setAttribute("sysUser", su);
            session.setAttribute("accessMap", accessRight(su));

            json = gson.toJson(new JsonReturnMsg("IEPM Login", "Success", "info"));
        }

        response.getWriter().println(json);
    }

    private HashMap accessRight(SystemUser su) {
        //AccessMap am= new AccessMap();
        HashMap am = new AccessMap().hm;

        String textToTokenize = (su.getRole().getRights() != null) ? su.getRole().getRights() : "";
        Scanner scanner = new Scanner(textToTokenize);
        scanner.useDelimiter(",");

        ArrayList acList = new ArrayList();
        while (scanner.hasNext()) {
            acList.add(scanner.next());
        }

        String[] accessRightsA = new String[acList.size()];
        for (int i = 0; i < acList.size(); i++) {
            accessRightsA[i] = (String) acList.get(i);
        }

        for (int i = 0; i < accessRightsA.length; i++) {
            if (am.containsKey(accessRightsA[i])) {
                am.remove(accessRightsA[i]);
                am.put(accessRightsA[i], "true");
            }
        }

        return am;
    }

    private void bufferInstantiation() {
        if (bFacade.getBuffers()) {
            bFacade.createBuffer();
        }
    }

    private void processLogout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        session.invalidate();

        json = gson.toJson(new JsonReturnMsg("IEPM Logout", "Success", "info"));
        response.getWriter().println(json);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
